package com.zhsj.OkeHomeConsumption.ui.fragment.minehome;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.empty.CityPartnerShopBean;
import com.zhsj.OkeHomeConsumption.empty.InviteBean;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.InvitePresenter;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.InviteUIInterFace;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class InviteFragment extends Fragment implements InviteUIInterFace {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;

    private InvitePresenter mInvitePresenter = null;
    private int flage = -1;


    private int pageCount = 0;
    private int pageIndex = 0;

    private List<InviteBean> mInviteList = null;

    private InviteAdapter mInviteAdapter = null;


    public static InviteFragment newInstance(int flage) {

        Bundle args = new Bundle();
        InviteFragment fragment = new InviteFragment();
        args.putInt("posion", flage);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        flage = getArguments().getInt("posion");

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_invite, null);
        unbinder = ButterKnife.bind(this, mView);
        initdata();
        return mView;
    }

    private void initdata() {
        mInvitePresenter = new InvitePresenter(getActivity(), this);
        mInvitePresenter.InviteGet(flage, 1);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);

        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);//传入false表示刷新失败
//                if (orderBeanList != null && orderBeanList.size() > 0) {
//                    orderBeanList.clear();
//                }
//                refreshLayout.setRefreshing(false);
                initRefersh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                NextPost();
            }
        });
    }

    public void initRefersh() {
        mInvitePresenter.InviteGet(flage, 1);
    }

    public void NextPost() {
        pageIndex++;
        mInvitePresenter.InviteGet(flage, pageIndex);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void InviteGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                pageIndex = jsonobj.optInt("pageIndex");
                pageCount = jsonobj.optInt("pageCount");
                JSONArray jsonArray = jsonobj.optJSONArray("data");
                if (pageIndex <= pageCount) {
                    mInviteList = new Gson().fromJson(jsonArray.toString(), new
                            TypeToken<ArrayList<InviteBean>>() {
                            }.getType());
                    mInviteAdapter = new InviteAdapter(mInviteList);
                    recyclerView.setAdapter(mInviteAdapter);

                } else {
                    Toast.makeText(getActivity(), "已经到最后一条", Toast.LENGTH_SHORT).show();
                }
                // 数据对接正常

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
//                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
//                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("InviteGet", "获取邀请的kehu");
        }
    }

    public class InviteAdapter extends BaseQuickAdapter<InviteBean, BaseViewHolder> {

        public InviteAdapter(@Nullable List<InviteBean> data) {
            super(R.layout.item_invite, data);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, InviteBean item) {
            helper.setText(R.id.name, item.getRuserName()).setText(R.id.phone, item.getPhone());

        }
    }
}
